//
//  GroupTableViewController.swift
//  testRxSwift
//
//  Created by 火星人 on 2017/7/26.
//  Copyright © 2017年 火星人. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources

class GroupTableViewController: BaseViewController {
    
    var tableView: UITableView!
    var disposed = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView = UITableView(frame: self.view.bounds)
        self.view.addSubview(tableView)
        tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "UITableViewCell")
        
        let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>()
        let items = Observable.just([
            SectionModel(model: "First", items:[
                1.0,
                2.0,
                3.0
                ]),
            SectionModel(model: "Second", items:[
                1.0,
                2.0,
                3.0
                ]),
            SectionModel(model: "Third", items:[
                1.0,
                2.0,
                3.0
                ])
            ])
        
        dataSource.configureCell = {
            (_, tv, indexPath, element) in
            let cell = tv.dequeueReusableCell(withIdentifier: "UITableViewCell")!
            cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
            return cell
        }
        
        dataSource.titleForHeaderInSection = {
            dataSource, sectionIndex in
            
            return dataSource[sectionIndex].model
        }
        
        items.bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: disposed)
        
        tableView.rx.itemSelected
            .map { indexPath in
                return (indexPath, dataSource[indexPath])
            }
            .subscribe(onNext: { indexPath, model in
                print("Tapped `\(model)` @ \(indexPath)")
            })
            .disposed(by: disposed)
    }

}
